// 技能渲染模块 - 专注于UI渲染逻辑
class SkillsManager {
    constructor() {
        this.skillsData = []; // 初始为空，等待异步加载
    }

    // 异步加载技能数据
    async loadSkillsData() {
        try {
            console.log('📡 开始加载技能数据...');
            const response = await fetch('/src/data/skills.json');
            
            if (!response.ok) {
                throw new Error(`数据加载失败: ${response.status}`);
            }
            
            const data = await response.json();
            this.skillsData = data.skills;
            console.log('✅ 技能数据加载成功:', this.skillsData.length, '项技能');
            return this.skillsData;
            
        } catch (error) {
            console.error('❌ 数据加载失败，使用默认数据:', error);
            // 降级方案：使用内置的默认数据
            this.skillsData = this.getFallbackData();
            return this.skillsData;
        }
    }

    // 降级数据（当JSON加载失败时使用）
    getFallbackData() {
        return [
            { id: 1, name: 'HTML5 & 语义化标签', level: 90, category: 'frontend' },
            { id: 2, name: 'CSS3 & 布局', level: 85, category: 'frontend' },
            { id: 3, name: 'JavaScript 基础编程', level: 70, category: 'programming' }
        ];
    }

    // 根据分类筛选技能
    getSkillsByCategory(category) {
        return this.skillsData.filter(skill => skill.category === category);
    }

    // 获取所有分类
    getCategories() {
        return [...new Set(this.skillsData.map(skill => skill.category))];
    }

    // 渲染单个技能条
    renderSkillItem(skill) {
        return `
            <div class="skill-item" data-category="${skill.category}" data-level="${skill.level}">
                <div class="skill-info">
                    <span class="skill-name">${skill.name}</span>
                    <span class="skill-percent">${skill.level}%</span>
                </div>
                <div class="skill-bar">
                    <div class="skill-progress" 
                         style="width: ${skill.level}%;"
                         data-level="${skill.level}">
                    </div>
                </div>
                ${skill.description ? `<p class="skill-desc">${skill.description}</p>` : ''}
            </div>
        `;
    }

    // 渲染技能筛选器
    renderCategoryFilter() {
        const categories = this.getCategories();
        if (categories.length <= 1) return ''; // 只有一个分类时不显示筛选器

        return `
            <div class="skills-filter">
                <button class="filter-btn active" data-category="all">全部</button>
                ${categories.map(cat => 
                    `<button class="filter-btn" data-category="${cat}">${this.getCategoryName(cat)}</button>`
                ).join('')}
            </div>
        `;
    }

    // 分类名称映射
    getCategoryName(category) {
        const nameMap = {
            'frontend': '前端技术',
            'programming': '编程语言', 
            'tools': '开发工具',
            'framework': '前端框架'
        };
        return nameMap[category] || category;
    }

    // 渲染完整技能列表
    renderSkillsList() {
        const filterHtml = this.renderCategoryFilter();
        const skillsHtml = this.skillsData.map(skill => this.renderSkillItem(skill)).join('');
        
        return filterHtml + skillsHtml;
    }

    // 初始化技能列表（异步）
    async initSkills() {
        const skillsContainer = document.getElementById('skills');
        
        // 显示加载状态
        skillsContainer.innerHTML = '<div class="loading">加载技能数据中...</div>';
        
        // 异步加载数据
        await this.loadSkillsData();
        
        // 渲染技能列表
        skillsContainer.innerHTML = this.renderSkillsList();
        
        // 绑定筛选事件
        this.bindFilterEvents();
        
        console.log('🎯 技能列表初始化完成');
    }

    // 绑定筛选器点击事件
    bindFilterEvents() {
        document.querySelectorAll('.filter-btn').forEach(btn => {
            btn.addEventListener('click', (e) => {
                const category = e.target.dataset.category;
                this.filterSkillsByCategory(category);
                
                // 更新激活状态
                document.querySelectorAll('.filter-btn').forEach(b => b.classList.remove('active'));
                e.target.classList.add('active');
            });
        });
    }

    // 根据分类筛选技能
    filterSkillsByCategory(category) {
        const allSkills = document.querySelectorAll('.skill-item');
        
        allSkills.forEach(skillItem => {
            if (category === 'all' || skillItem.dataset.category === category) {
                skillItem.style.display = 'block';
            } else {
                skillItem.style.display = 'none';
            }
        });
    }
}

// 创建全局实例
const skillsManager = new SkillsManager();

// 导出初始化方法
export async function initSkills() {
    await skillsManager.initSkills();
}

// 导出其他可能用到的方法
export { skillsManager };